<template>
    <div class="order-detail-container" v-if="orderDetail">
        <!-- 头部信息 -->
        <DetailAction :orderDetail="orderDetail" @updateOrderStatus="updateOrderStatus" @handleShowEvaluate="handleShowEvaluate"/>


        <!-- 物流信息区域开始 -->
        <div class="logistic-wrap">
            <div class="logistic-title">
                <i class="iconfont icon-wuliupeisong"></i>
                <span>物流信息</span>
            </div>
            <div class="logistic-content" v-if="orderLogistics.length > 0">
                <el-collapse>
                    <el-collapse-item :title="orderLogistics[0].message" name="1">
                        <el-timeline>
                            <el-timeline-item
                                v-for="(item, index) in orderLogistics"
                                :key="index"
                                :color="index == 0 ? '#27ba9b' : ''"
                                :timestamp="item.create_time"
                            >
                                {{ item.message }}
                            </el-timeline-item>
                        </el-timeline>
                    </el-collapse-item>
                </el-collapse>
            </div>
            <TridentEmpty v-else/>
        </div>
        <!-- 物流信息区域结束 -->

        <!-- 商品信息区域开始 -->
        <div class="goods-wrap">
            <div class="goods-title">
                <i class="iconfont icon-shangpin"></i>
                <span>商品信息</span>
            </div>
            <div class="goods-content">
                <el-card style="width: 460px;margin-right: 20px;margin-bottom: 10px;cursor: pointer;" v-for="(item, index) in orderDetail.order.orderItems" :key="index">
                    <template #header>
                        <div class="card-header">
                            <span style="line-height: 20px;">{{item.goods_name}}</span>
                        </div>
                    </template>
                    <div class="goods-body" @click="$router.push({path: '/goods-detail', query: {id: item.goods_id}})">
                        <div class="goods-cover">
                            <img :src="global.FILE_DOMAIN + item.goods_cover_url" alt="">
                        </div>

                        <div class="goods-info">
                            <!-- 商品SKU -->
                            <span class="goods_sku_text ellipsis-2">{{ item.goods_sku_text }}</span>
                            <!-- 价格区域 -->
                            <div class="price-wrap">
                                <div class="price-item">
                                    <span class="title">单价：</span>
                                    <span>￥{{ (item.goods_price/100).toFixed(2) }}</span>
                                </div>

                                <div class="price-item">
                                    <span class="title">数量：</span>
                                    <span class="num">{{ item.goods_num }}</span>
                                </div>
                            </div>

                            <div class="subtotal-wrap">
                                <span>小计：</span>
                                <span class="symbol">￥</span>
                                <span class="subtotal">{{ ((item.goods_price * item.goods_num)/100).toFixed(2) }}</span>
                            </div>
                        </div>
                    </div>
                    <template #footer>
                        <div class="footer-wrap">
                            <div class="right-box">
                                <span>实付金额：</span>
                                <span class="symbol">￥</span>
                                <span class="pay_money">{{ ((item.pay_money * item.goods_num)/100).toFixed(2) }}</span>
                            </div>

                            <!-- 待评价状态: 展示评价按钮 -->
                            <el-button type="primary" @click="handleShowEvaluate(item)" v-if="[6].includes(item.status) && orderDetail.order.orderItems.length > 1">去评价</el-button>

                            <el-button type="primary" @click="handleShowEvaluate(item)" v-if="[7].includes(orderDetail.order.status) && orderDetail.order.orderItems.length > 1">追加评价</el-button>
                            
                            
                        </div>
                    </template>
                </el-card>
            </div>

            <!-- 订单金额 -->
            <div class="order-amount">
                <div class="amount-item">
                    <span>商品总价：</span>
                    <span>￥</span>
                    <span class="total-amount">{{ (orderDetail.order.order_money/100).toFixed(2) }}</span>
                </div>

                <div class="amount-item">
                    <span>应付金额：</span>
                    <span class="symbol">￥</span>
                    <span class="amount">{{ (orderDetail.order.pay_money/100).toFixed(2) }}</span>
                </div>
            </div>
        </div>
        <!-- 商品信息区域结束 -->

        <!-- 收货信息区域开始 -->
        <div class="address-wrap">
            <div class="address-title">
                <i class="iconfont icon-address"></i>
                <span>收货地址</span>
            </div>
            <div class="address-content">
                <div class="address-item">
                    <span class="title">收货人：</span>
                    <span>{{ orderDetail.order_delivery_addr.name }}</span>
                </div>

                <div class="address-item">
                    <span class="title">手机号：</span>
                    <span>{{ orderDetail.order_delivery_addr.mobile }}</span>
                </div>

                <div class="address-item">
                    <span class="title">收货地址：</span>
                    <span>{{ orderDetail.order_delivery_addr.region }} {{ orderDetail.order_delivery_addr.address }}</span>
                </div>
            </div>
        </div>
        <!-- 收货信息区域结束 -->

        <!-- 评价弹层开始 -->
        <el-dialog
            v-model="evaluateDialogVisible"
            :close-on-click-modal="false"
            title="评价商品"
            width="700"
        >
        <!-- 评价的商品区域 -->
        <div class="evaluate-goods-wrap">
            <!-- 商品图片区域 -->
            <div class="cover-image">
                <img :src="global.FILE_DOMAIN + evaluateGoods.goods_cover_url" alt="">
            </div>

            <div class="goods-info">
                <div class="goods-sku-txt ellipsis-2">{{evaluateGoods.goods_sku_text}}</div>
                <div class="goods-name ellipsis-1">{{evaluateGoods.goods_name}}</div>
            </div>
        </div>

        <!-- 表单区域 -->
        <div class="form-wrap">
            <el-form :model="formParams" ref="refForm">
                <!-- 评价内容 -->
                <el-input
                    v-model="formParams.contents"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    type="textarea"
                    placeholder="请输入评价内容"
                />

                <!-- 评价图片 -->
                <el-form-item style="padding-top: 10px;">
                    <el-upload
                        class="avatar-uploader"
                        :action="global.FILE_SERVER + '/api/v1/image/minioSingleUploadImage'"
                        :file-list="imageList"
                        list-type="picture-card"
                        :limit="3"
                        :on-success="handleEvaluateImageSuccess"
                        :before-upload="beforeEvaluateImageUpload"
                    >
                        <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                        <template #tip>
                            <div class="el-upload__tip">只能上传jpg/png文件,且不超过500kb,最多上传3张图片</div>
                        </template>
                    </el-upload>
                </el-form-item>

                <!-- 评分 -->
                <div class="rate-wrap" v-if="status == 6">
                    <!-- 综合评价 -->
                    <div class="rate-item">
                    <span class="rate-text">综合评价</span>
                    <el-rate
                        v-model="formParams.composite_score"
                        size="large"
                        :icons="['BellFilled', 'BellFilled', 'BellFilled']"
                        void-icon="Bell"
                        :colors="['#27BA9B', '#27BA9B', '#27BA9B']"
                    />
                    </div>

                    <!-- 描述相符 -->
                    <div class="rate-item">
                    <span class="rate-text">描述相符</span>
                    <el-rate
                        v-model="formParams.conform_score"
                        size="large"
                        color="#27BA9B"
                    />
                    </div>

                    <!-- 物流服务 -->
                    <div class="rate-item">
                    <span class="rate-text">物流服务</span>
                    <el-rate
                        v-model="formParams.logistic_score"
                        size="large"
                    />
                    </div>

                    <!-- 服务态度 -->
                    <div class="rate-item">
                    <span class="rate-text">服务态度</span>
                    <el-rate
                        v-model="formParams.serve_score"
                        size="large"
                    />
                    </div>
                </div>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
            <el-button @click="evaluateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEvaluateSubmit">发布</el-button>
            </div>
        </template>
        </el-dialog>
        <!-- 评价弹层结束 -->
    </div>
</template>

<script setup>
// 引入组件
import DetailAction from './components/DetailAction.vue';

import { ref, onMounted, inject, reactive } from 'vue'
import {useRoute} from 'vue-router'

import { reqOrderDetailAPI } from '@/apis/order'
import { reqAddGoodsCommentAPI, reqAppendGoodsCommentAPI } from '@/apis/goodsEvaluate'

import { useUserStore } from '@/stores/modules/user'

import { ElNotification, ElMessage, ElLoading } from 'element-plus'


// ------------- 定义全局变量开始 -------------
const route = useRoute()

// 订单详情数据
const orderDetail = ref(null)

// 订单数据
const order = ref(null)

// 订单步骤数据
const orderSteps = ref([])

// 订单物流
const orderLogistics = ref([])

// 获取全局对象
const global = inject('global')

// 用户存储
const userStore = useUserStore()

// 加载实例
let loadingInstance = null
// ------------- 定义全局变量结束 -------------



// ------------- 挂载页面完成开始 -------------
onMounted(() => {
  getOrderDetail()
})
// ------------- 挂载页面完成结束 -------------



// ------------- 获取订单详情开始 -------------
const getOrderDetail = async () => {
  const result = await reqOrderDetailAPI(route.params.id, 1)
  if (result.code == 200) {
    // 订单详情数据
    orderDetail.value = result.data
    
    // 订单数据
    order.value = result.data.order

    orderLogistics.value = result.data.order_logistics != null ? result.data.order_logistics : []
  }
}
// ------------- 获取订单详情结束 -------------



// ------------- 评价商品功能开始 -------------
// 定义评价商品
const evaluateGoods = ref({})

// 表单参数
const formParams = reactive({
    oid: 0,
    order_item_id: 0,
    goods_id: 0,
    goods_name: '',
    goods_sku_id: 0,
    goods_sku_text: '',
    username: userStore.profile.user.username,
    avatar_url: userStore.profile.user.avatar_url,
    contents: '',
    image_url: '',
    composite_score: 0,
    conform_score: 0,
    logistic_score: 0,
    serve_score: 0,
    is_append: 0
})

// 图片
const imageList = ref([])

// 是否显示评价弹层
const evaluateDialogVisible = ref(false)

const status = ref(0)
// 处理显示评价弹层
const handleShowEvaluate = (item) => {
  evaluateGoods.value = item

  formParams.oid = item.oid
  formParams.order_item_id = item.id
  formParams.goods_id = item.goods_id
  formParams.goods_name = item.goods_name
  formParams.goods_sku_id = item.goods_sku_id
  formParams.goods_sku_text = item.goods_sku_text

  status.value = item.status

  // 重置表单数据
  formParams.contents = ''
  formParams.image_url = ''
  formParams.composite_score = 0
  formParams.conform_score = 0
  formParams.logistic_score = 0
  formParams.serve_score = 0
  imageList.value = []

  // 显示评价弹层
  evaluateDialogVisible.value = true
}

// 选择评价图片上传之前
const beforeEvaluateImageUpload = async (file) => {
  // 加载提示框
  loadingInstance = ElLoading.service({
    text: '正在上传中',
    background: 'rgba(0, 0, 0, 0.8)'
  })

  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
      ElNotification.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
      ElNotification.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M || isPNG && isLt2M;
}

// 上传评价图片成功
const handleEvaluateImageSuccess = (res) => {
  // 关闭加载提示
  loadingInstance.close()

  if (res.code != 200) {
    ElNotification.error(res.message)
    return false
  }

  imageList.value.push({
    url: res.data.absolute_image_url,
    image_url: res.data.image_url
  })
}

// 提交评价
const handleEvaluateSubmit = async () => {
  if (formParams.contents == '') {
    ElMessage.error('请输入评价内容')
      return false
  }

  if (status.value == 6) {
    // 提交参数判断
    if (formParams.composite_score == 0) {
      ElMessage.error('请选择综合评分')
      return false
    }
    if (formParams.conform_score == 0) {
      ElMessage.error('请选择描述相符评分')
      return false
    }
    if (formParams.logistic_score == 0) {
      ElMessage.error('请选择物流服务评分')
      return false
    }
    if (formParams.serve_score == 0) {
      ElMessage.error('请选择服务态度评分')
      return false
    }
  }

  // 组装图片数据
  let image_url = ''
  if (imageList.value.length > 0) {
    imageList.value.forEach(value => {
      image_url += value.image_url + ','
    });
  }

  formParams.image_url = image_url.substring(0,image_url.length-1)

  if (status.value == 7) {
    formParams.is_append = 1
    // 请求追加评价接口
    await reqAppendGoodsCommentAPI(formParams)
    ElNotification({type: 'success', message: '追评成功'})
  } else {
    // 请求新增评价接口
    await reqAddGoodsCommentAPI(formParams)
    ElNotification({type: 'success', message: '评价成功'})


    // 判断该订单是否存在未评价的商品
    let flag = false
    orderDetail.value.order.orderItems.forEach(item => {
        // 查找订单明细，将其状态设置为：已完成
        if (item.id == formParams.order_item_id) {
            item.status = 7
        }

        if (item.status == 6) {
            flag = true
        }
    })

    // 修改订单状态
    if (!flag) {
        updateOrderStatus(7)
    }
  }

  evaluateDialogVisible.value = false
}
// ------------- 评价商品功能结束 -------------



// ------------- 更新订单状态开始 -------------
const updateOrderStatus = (status) => {
    orderDetail.value.order.status = status
}
// ------------- 更新订单状态结束 -------------
</script>

<style scoped lang="scss">
.order-detail-container {
    // 物流区域
    .logistic-wrap {
        background-color: #fff;
        margin-top: 10px;
        padding: 20px;
        .logistic-title {
            display: flex;
            align-items: center;
            font-size: 18px;
            border-bottom: 1px solid #f5f5f5;
            padding-bottom: 20px;
            .iconfont {
                margin-right: 5px;
                font-size: 25px;
                color: $main-color;
            }
        }
        .logistic-content {
            padding-top: 10px;
            ::v-deep(.el-collapse-item__content) {
                padding-left: 2px;
            }
        }
    }

    // 商品区域
    .goods-wrap {
        background-color: #fff;
        margin-top: 10px;
        padding: 20px;
        .goods-title {
            font-size: 18px;
            margin-bottom: 20px;
            .iconfont {
                color: $main-color;
                font-size: 25px;
                margin-right: 5px;
            }
        }

        .goods-content {
            display: flex;
            flex-wrap: wrap;
            .goods-body {
                display: flex;
                align-items: center;
                // 商品图片
                .goods-cover {
                    width: 80px;
                    height: 80px;
                    img {
                        width: 100%;
                        height: 100%;
                    }
                }

                .goods-info {
                    flex: 1;
                    padding-left: 10px;
                    .goods_sku_text {
                        color: #666;
                        line-height: 24px;
                        background-color: #f5f5f5;
                        padding: 5px;
                    }
                    .price-wrap {
                        padding-top: 14px;
                        display: flex;
                        justify-content: space-between;
                        .price-item {
                            margin-right: 10px;
                            &:last-child {
                                margin-right: 0;
                            }
                            .title {
                                color: #666;
                            }
                        }
                    }
                    .subtotal-wrap {
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;
                        padding-top: 20px;
                        .symbol {
                            color: #666;
                        }
                        .subtotal {
                            font-size: 18px;
                        }
                    }
                }
            }
            .footer-wrap {
                display: flex;
                justify-content: space-between;
                align-items: center;
                .right-box {
                    .symbol {
                        color: $price-color;
                    }
                    .pay_money {
                        font-size: 18px;
                        color: $price-color;
                    }
                }
            }
        }

        .order-amount {
            margin-top: 10px;
            border-top: 2px solid #f5f5f5;
            padding-top: 10px;
            .amount-item {
                display: flex;
                justify-content: flex-end;
                align-items: flex-end;
                padding: 10px 0;
                .symbol {
                    color: $price-color;
                }
                .amount {
                    color: $price-color;
                    font-size: 20px;
                    font-weight: bold;
                }
                .total-amount {
                    font-size: 18px;
                }
            }
        }
    }

    // 地址区域
    .address-wrap {
        background-color: #fff;
        margin-top: 10px;
        padding: 20px;
        .address-title {
            display: flex;
            align-items: center;
            font-size: 18px;
            border-bottom: 1px solid #f5f5f5;
            padding-bottom: 20px;
            .iconfont {
                margin-right: 5px;
                font-size: 25px;
                color: $main-color;
            }
        }
        .address-content {
            padding-top: 10px;
            .address-item {
                padding: 10px 0;
                .title {
                    color: #666;
                }
            }
        }
    }

    // 评价商品区域
    .evaluate-goods-wrap {
        display: flex;
        align-items: center;
        border-top: 1px solid #f5f5f5;
        padding-top: 10px;
        .cover-image {
            width: 70px;
            height: 70px;
            img {
                width: 100%;
                height: 100%;
            }
        }
        .goods-info {
            flex: 1;
            padding-left: 10px;
            .goods-sku-txt {
                font-size: 15px;
                font-weight: bold;
                line-height: 18px;
            }
            .goods-name {
                font-size: 16px;
                margin-top: 10px;
                padding-bottom: 2px;
            }
        }
    }

    // 评价表单区域
    .form-wrap {
        padding-top: 10px;
        .rate-wrap {
            .rate-item {
                display: flex;
                align-items: center;
                .rate-text {
                    font-size: 18px;
                    padding-right: 10px;
                }
                ::v-deep(.el-rate .el-rate__icon) {
                    font-size: 26px;
                }
            }
        }
    }
}
</style>